import React, { Component } from 'react';

import { Card, Form, Input, Button, Checkbox, Tabs,  Icon,message} from 'antd';

import $ from 'jquery';

import { ajax, fetchData } from './common';

import UIIcon from './uicomponents/UIIcon';

import './loginPage.css';

const { Meta } = Card;

const TabPane = Tabs.TabPane;
	
const FormItem = Form.Item;
		

class WeixinLoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            processLogin: false,
            //weixinLoginQrCode: encodeURIComponent(fetchData('common/getConfig', { key: 'weixin.loginQrCode' })),
        };
    }

    componentDidMount() {

    }

    render() {
        const { weixinLoginQrCode, weixinCheckLoginUrl } = this.state;
        return (
            <Card style={{ width: 200 }}>
                <Meta title={<span><Icon type="wechat" />微信扫码登录</span>}/>
            </Card>
        );
    }
}

class AppLoginForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            processLogin: false,
            account: '',
            password: '',
            remember: false,
            appConfig : fetchData('SYSTEM/APP/getSystemConfig',{configType : 'APPLICATION'}),
            //weixinLoginQrCode: encodeURIComponent(fetchData('common/getConfig', { key: 'weixin.loginQrCode' })),
        };
    }

    componentDidMount () {
        this._mounted = true;
        const {appConfig} = this.state;
        $('title').text(appConfig.appName);
     }
     componentWillUnmount () {
        this._mounted = false
     }

    handleSubmit = (e) => {

        if(this._mounted === true){
            const {onLogin} = this.props;

            e.preventDefault();
            this.setState({ processLogin: true });
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    
                    ajax('SYSTEM/auth/login',values).then((data) => {

                        if(data.hasError === true){
                            message.error(data.message);
                        }
                        else if(onLogin !== undefined){
                            setTimeout(() => {
                                onLogin(data);
                            });
                        }

                    }).catch(err => {
                        //console.log(err);
                        message.error(err);
                    }).finally(() => {
                        this.setState({ processLogin: false });
                    });
            
                }
                else {
                    this.setState({ processLogin: false });
                }
            });
        }

        
    }

    weixinLogin = (userInfo) => {
        if (userInfo !== null && userInfo !== "") {
            //var owner = this;
            // doWeixinLogin(userInfo, function (data) {
            //     if (data.hasError == true) {
            //         message.error(data.message);
            //     }
            //     else {
            //         clearInterval(owner.timerID);
            //     }
            // });
        }
    }

    onLoginTypeChange = (activeKey) => {
        if ('wechatType' === activeKey) {
            let weixinCheckLoginUrl = '';//fetchData('common/getConfig', { key: 'weixin.checkLoginUrl' });
            let userSessionId = '';//fetchData('common/getSessionId');
            var owner = this;
            this.timerID = setInterval(
                 () => {
                    ajax(weixinCheckLoginUrl,
                        { params: { sessionId: userSessionId, needClear: true } },
                        { headers: { 'Access-Control-Allow-Origin': '*' } }
                    ).then(res => {
                        owner.weixinLogin(res.data);
                    });
                },
                1000
            );
        }
        else {
            clearInterval(this.timerID);
        }
    }

    render() {

        const { getFieldDecorator } = this.props.form;

        const {appConfig} = this.state;

        return (

            <div className="loginContent">
                <div className="top">
                    <div className="header">
                        <span className="title"><UIIcon icon={appConfig.appIcon} fixedWidth={true}/>{appConfig.appName}</span>
                    </div>
                    <div className="desc">{appConfig.desc}</div>
                </div>

                <Tabs defaultActiveKey="accountType" animated={false} onChange={this.onLoginTypeChange}>
                    <TabPane tab="帐号密码登录" key="accountType">
                        <div align='center'>
                            <Form id="loginForm" onSubmit={this.handleSubmit} className="login-form">
                                <FormItem>
                                    {getFieldDecorator('account', {
                                        rules: [{ required: true, message: '请输入用户名!' }],
                                    })(
                                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
                                    )}
                                </FormItem>
                                <FormItem>
                                    {getFieldDecorator('password', {
                                        rules: [{ required: true, message: '请输入密码!' }],
                                    })(
                                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
                                    )}
                                </FormItem>
                                <FormItem>
                                    {getFieldDecorator('remember', {
                                        valuePropName: 'checked',
                                        initialValue: true
                                    })(
                                        <Checkbox>记住我</Checkbox>
                                    )}
                                    <a className="login-form-forgot" href="">忘记密码</a>
                                    <Button type="primary" htmlType="submit" className="login-form-button" loading={this.state.processLogin}>
                                        登 录
                                    </Button>
                                </FormItem>
                            </Form>
                        </div>
                    </TabPane>
                    <TabPane tab="微信扫码登录" key="wechatType">
                        <WeixinLoginForm />
                    </TabPane>
                </Tabs>
            </div>

        );
    }
}

export default Form.create()(AppLoginForm);